<template>
  <div class="resource-view">
    <!-- 滚动和内容区域 -->
    <div ref="scrollContainerRef" class="scroll-container" @scroll="handleScroll">
      <!-- 错误状态 -->
      <div v-if="error" class="state-container error-state">
        <AxiomText color="danger">加载失败: {{ error.message }}</AxiomText>
        <AxiomButton @click="$emit('loadMore')" :disabled="loading">重试</AxiomButton>
      </div>

      <!-- 布局容器 -->
      <div :class="layoutClass">
        <!-- 内置的、由配置驱动的通用卡片渲染 -->
        <AxiomCard v-for="item in items" :key="item.id || item[itemConfig.keyField]" class="resource-card">
          <!-- Card Header -->
          <div class="card-header">
            <AxiomText weight="medium" class="card-title">{{ item[itemConfig.titleField] }}</AxiomText>
            <span v-if="itemConfig.subtitleField" class="card-subtitle">{{ item[itemConfig.subtitleField] }}</span>
          </div>
          <!-- Card Body -->
          <div class="card-body">
            <AxiomText size="small" color="secondary" class="card-description">
              {{ item[itemConfig.descriptionField] || '暂无描述' }}
            </AxiomText>
            <div v-if="itemConfig.tag" class="card-meta">
              <AxiomText size="small" color="tertiary">
                {{ itemConfig.tag.prefix }}{{ item[itemConfig.tag.field] }}
              </AxiomText>
            </div>
          </div>
          <!-- Card Footer -->
          <div v-if="itemConfig.status" class="card-footer">
            <span :class="getStatusClass(item)">
              {{ getStatusText(item) }}
            </span>
          </div>
        </AxiomCard>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="state-container loading-state">
        <AxiomLoading />
        <AxiomText color="secondary">加载中...</AxiomText>
      </div>

      <!-- 结束/空状态 -->
      <div v-if="finished && items.length === 0 && !loading" class="state-container empty-state">
        <AxiomText color="secondary">暂无数据</AxiomText>
      </div>
      <div v-if="finished && items.length > 0 && !loading" class="state-container finished-state">
        <AxiomText color="secondary">没有更多了</AxiomText>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import AxiomText from '../common/AxiomText.vue';
import AxiomButton from '../common/AxiomButton.vue';
import AxiomCard from '../common/AxiomCard.vue';
import AxiomLoading from '../common/AxiomLoading.vue';

const props = defineProps({
  items: { type: Array, required: true },
  loading: { type: Boolean, default: false },
  finished: { type: Boolean, default: false },
  error: { type: Object, default: null },
  itemConfig: { type: Object, required: true },
  layout: { type: String, default: 'grid', validator: (value) => ['grid', 'list'].includes(value) },
  gridColumns: { type: Object, default: () => ({ sm: 1, md: 2, lg: 3, xl: 4 }) },
  scrollThreshold: { type: Number, default: 200 }
});

const emit = defineEmits(['loadMore']);

const scrollContainerRef = ref(null);

const layoutClass = computed(() => {
  if (props.layout === 'grid') {
    return Object.entries(props.gridColumns).reduce((classes, [breakpoint, cols]) => {
      return `${classes} grid-cols-${breakpoint}-${cols}`;
    }, 'grid-layout');
  }
  return 'list-layout';
});

const handleScroll = () => {
  if (props.loading || props.finished || props.error) return;
  
  const container = scrollContainerRef.value;
  if (!container) return;
  
  const { scrollHeight, scrollTop, clientHeight } = container;
  if (scrollHeight - scrollTop - clientHeight < props.scrollThreshold) {
    emit('loadMore');
  }
};

onMounted(() => {
  if (scrollContainerRef.value) {
    scrollContainerRef.value.addEventListener('scroll', handleScroll, { passive: true });
  }
});

onBeforeUnmount(() => {
  if (scrollContainerRef.value) {
    scrollContainerRef.value.removeEventListener('scroll', handleScroll);
  }
});

const getStatusText = (item) => {
  const config = props.itemConfig.status;
  if (!config) return '';
  return item[config.field] ? config.trueText : config.falseText;
};

const getStatusClass = (item) => {
  const config = props.itemConfig.status;
  if (!config) return '';
  const baseClass = 'status-badge';
  const statusClass = item[config.field] ? config.trueClass : config.falseClass;
  return [baseClass, statusClass];
};
</script>

<style lang="scss">
@use '../../styles/components/mobile/axiom-resource-view';
</style>